package org.dromara.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.domain.PlanSum;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.RandomUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.*;
import org.dromara.system.domain.bo.AppProcurementDetailBo;
import org.dromara.system.domain.bo.TotalPlanBo;
import org.dromara.system.domain.vo.AppProcurementDetailVo;
import org.dromara.system.domain.vo.TotalPlanVo;
import org.dromara.system.mapper.*;
import org.dromara.system.service.*;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.AppProcurementPlanBo;
import org.dromara.system.domain.vo.AppProcurementPlanVo;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 采购计划Service业务层处理
 *
 * @author Lion Li
 * @date 2025-09-12
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AppProcurementPlanServiceImpl implements IAppProcurementPlanService {

    private final AppProcurementPlanMapper baseMapper;
    private final IAppProcurementDetailService iAppProcurementDetailService;
    private final AppProcurementDetailMapper appProcurementDetailMapper;
    private final IAppCategoryService iAppCategoryService;
    private final IAppMaterialService iAppMaterialService;
    private final AppOrderMapper appOrderMapper;
    private final AppWarehouseMapper appWarehouseMapper;
    private final AppWarehouseRecordMapper appWarehouseRecordMapper;
    private final AppSupplierDetailMapper appSupplierDetailMapper;
    private final SysTenantMapper sysTenantMapper;
    /**
     * 查询采购计划
     *
     * @param id 主键
     * @return 采购计划
     */
    @Override
    public AppProcurementPlanVo queryById(Long id){
        //如果是年度计划 则只查这一个
        //如果是季度计划 则需要把年度和他下面的季度查出来
        //如果是月计划 则需要查出季度 和下面的月计划

        LambdaQueryWrapper<AppProcurementPlan> appProcurementPlanLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        appProcurementPlanLambdaQueryWrapper1.eq(AppProcurementPlan::getId,id);
        AppProcurementPlan appProcurementPlanVo1 = baseMapper.selectOne(appProcurementPlanLambdaQueryWrapper1);

        if (appProcurementPlanVo1 == null){
            appProcurementPlanLambdaQueryWrapper1.clear();
            appProcurementPlanLambdaQueryWrapper1.eq(AppProcurementPlan::getPlanCode,id);
            AppProcurementPlan zui = baseMapper.selectOne(appProcurementPlanLambdaQueryWrapper1);
            if (zui == null){
                throw new RuntimeException("采购计划不存在");
            }else {
                appProcurementPlanVo1 = zui;
            }

        }

        AppProcurementPlanVo appProcurementPlanVo = BeanUtil.copyProperties(appProcurementPlanVo1, AppProcurementPlanVo.class);

        //设置发货地址
        LambdaQueryWrapper<AppOrder> appOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appOrderLambdaQueryWrapper.eq(AppOrder::getPlanId,appProcurementPlanVo1.getPlanCode());
        List<AppOrder> appOrderVos = appOrderMapper.selectList(appOrderLambdaQueryWrapper);
        if (!CollUtil.isEmpty(appOrderVos)){
            appProcurementPlanVo.setDeliveryAddress(CollUtil.getLast(appOrderVos).getDeliveryAddress());
            appProcurementPlanVo.setOrderStatus(CollUtil.getLast(appOrderVos).getOrderStatus());
            appProcurementPlanVo.setOrderId(CollUtil.getLast(appOrderVos).getOrderId());
        }


        if (appProcurementPlanVo != null){
            Map<Long,String> materMap =  iAppMaterialService.selAllMap();
            Map<Long,String> categoryMap = iAppCategoryService.selAllMap();
            //查询下面的采购详情
           List<AppProcurementDetail> appProcurementDetailVos = iAppProcurementDetailService.
               queryListByPlanCode(appProcurementPlanVo.getPlanCode());
           //查询原料类型和种类
            if (!CollUtil.isEmpty(appProcurementDetailVos)){
                //查询所有原料 以及种类
                for (AppProcurementDetail appProcurementDetail : appProcurementDetailVos) {
                    appProcurementDetail.setMaterialName(materMap.get(appProcurementDetail.getMaterialTypeId()));
                    appProcurementDetail.setCategoryName(categoryMap.get(appProcurementDetail.getCategoryId()));
                }
            }
            //结束
           appProcurementPlanVo.setAppProcurementDetailVos(appProcurementDetailVos);
            //供应商信息
            if (appProcurementPlanVo1.getSupplierId()!=null){
                AppSupplierDetail appSupplierDetail = appSupplierDetailMapper.selectOne(new LambdaQueryWrapper<AppSupplierDetail>().eq(AppSupplierDetail::getId, appProcurementPlanVo1.getSupplierId()));
                appProcurementPlanVo.setSupplierName(appSupplierDetail.getSupplierName());
            }

            if (appProcurementPlanVo.getPid()==null){
                return appProcurementPlanVo;
            }
            //父计划在外层
            //查询父计划 以及父计划下的小计划
            LambdaQueryWrapper<AppProcurementPlan> appProcurementPlanLambdaQueryWrapper = new LambdaQueryWrapper<>();
            appProcurementPlanLambdaQueryWrapper.eq(AppProcurementPlan::getPid,appProcurementPlanVo.getPid());
            List<AppProcurementPlanVo> appFProcurementPlanVos = baseMapper.selectVoList(appProcurementPlanLambdaQueryWrapper);
            if (!CollUtil.isEmpty(appFProcurementPlanVos)){
                for (int i = 0; i < appFProcurementPlanVos.size(); i++) {
                    //查询下面的采购详情
                    List<AppProcurementDetail> apProcurementDetailVo = iAppProcurementDetailService.
                        queryListByPlanCode(appFProcurementPlanVos.get(i).getPlanCode());
                    if (!CollUtil.isEmpty(apProcurementDetailVo)){
                        for (AppProcurementDetail appProcurementDetail : apProcurementDetailVo) {
                            appProcurementDetail.setMaterialName(materMap.get(appProcurementDetail.getMaterialTypeId()));
                            appProcurementDetail.setCategoryName(categoryMap.get(appProcurementDetail.getCategoryId()));
                        }
                        appFProcurementPlanVos.get(i).setAppProcurementDetailVos(apProcurementDetailVo);
                    }
                }



            }
            appProcurementPlanVo.setAppChildPlanVos(appFProcurementPlanVos);
        }
        return appProcurementPlanVo;
    }

    /**
     * 分页查询采购计划列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 采购计划分页列表
     */
    @Override
    public TableDataInfo<AppProcurementPlanVo> queryPageList(AppProcurementPlanBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppProcurementPlan> lqw = buildQueryWrapper(bo);

        //订单状态查询采购
        if (bo.getOrderStatus()!=null){
            LambdaQueryWrapper<AppOrder> aoq = new LambdaQueryWrapper<>();
            aoq.eq(AppOrder::getOrderStatus,bo.getOrderStatus());
            List<AppOrder> appOrders = appOrderMapper.selectList(aoq);
            if (!CollUtil.isEmpty(appOrders)){
                List<String> planId = appOrders.stream().map(AppOrder::getPlanId).toList();
                lqw.in(AppProcurementPlan::getPlanCode,planId);
            }else {
                return TableDataInfo.build(new Page<>());
            }
        }

        if (bo.getType()!=null){
            if (bo.getType()==1 || bo.getType()==3){
                //1->抢单大厅
                LambdaQueryWrapper<AppOrder> aoq = new LambdaQueryWrapper<>();
                if (bo.getType()==1){
                    aoq.eq(AppOrder::getOrderStatus,2);
                    aoq.isNull(AppOrder::getDriverId);
                }else if (bo.getType()==3){
                    aoq.eq(AppOrder::getOrderStatus,5);
                    aoq.eq(AppOrder::getDriverId,LoginHelper.getUserId());
                }
                List<AppOrder> appOrders = appOrderMapper.selectList(aoq);
                if (!CollUtil.isEmpty(appOrders)){
                    System.err.println(appOrders.get(0).getDriverId());
                    List<String> planId = appOrders.stream().filter(a -> a.getDriverId()==null).map(AppOrder::getPlanId).toList();
                    //筛选出已入库的订单
                    if (bo.getType()==3){
                        List<AppWarehouseRecord> appWarehouseRecords = appWarehouseRecordMapper.selectList();
                        if (!CollUtil.isEmpty(appWarehouseRecords)) {
                            List<String> list = appWarehouseRecords.stream().map(AppWarehouseRecord::getPlanCode).toList();
                            //过滤掉已入库的
                            planId = planId.stream().filter(a -> !list.contains(a)).toList();
                        }
                    }
                    if (!CollUtil.isEmpty(planId)){
                        lqw.in(AppProcurementPlan::getPlanCode,planId);
                    }
                }else {
                    return TableDataInfo.build(new Page<>());
                }
            }
            if (bo.getType()==2){
                // 2->待确认承运 已经被自己接过单子
                LambdaQueryWrapper<AppOrder> aoq = new LambdaQueryWrapper<>();
                aoq.eq(AppOrder::getDriverId, LoginHelper.getUserId());
                aoq.eq(AppOrder::getOrderStatus,2);
                aoq.isNotNull(AppOrder::getDriverId);
                List<AppOrder> appOrders = appOrderMapper.selectList(aoq);
                if (!CollUtil.isEmpty(appOrders)){
                    List<String> planId = appOrders.stream().map(AppOrder::getPlanId).toList();
                    lqw.in(AppProcurementPlan::getPlanCode,planId);
                    lqw.in(AppProcurementPlan::getStayCarrier,0);
                }else {
                    return TableDataInfo.build(new Page<>());
                }
            }

            //4->待验订单
            if (bo.getType()==4){
                LambdaQueryWrapper<AppOrder> aoq = new LambdaQueryWrapper<>();
                aoq.eq(AppOrder::getOrderStatus,5);
                List<AppOrder> appOrders = appOrderMapper.selectList(aoq);
                if (!CollUtil.isEmpty(appOrders)){
                    //质检信息需为空
                    appOrders = appOrders.stream().filter(appOrder -> appOrder.getQualityId()==null).collect(Collectors.toList());
                    if (CollUtil.isEmpty(appOrders)){
                        return TableDataInfo.build(new Page<>());
                    }
                    List<String> planId = appOrders.stream().map(AppOrder::getPlanId).toList();
                    lqw.in(AppProcurementPlan::getPlanCode,planId);
                }else {
                    return TableDataInfo.build(new Page<>());
                }
            }






            //5->质检完成订单
            if (bo.getType()==5){
                LambdaQueryWrapper<AppOrder> aoq = new LambdaQueryWrapper<>();
                aoq.isNotNull(AppOrder::getQualityId);
                List<AppOrder> appOrders = appOrderMapper.selectList(aoq);
                if (!CollUtil.isEmpty(appOrders)){
                    List<String> planId = appOrders.stream().map(AppOrder::getPlanId).toList();
                    lqw.in(AppProcurementPlan::getPlanCode,planId);
                }else {
                    return TableDataInfo.build(new Page<>());
                }
            }
            //财务员  type  6->待结算  7->已结算
            if (bo.getType()==6 || bo.getType()==7){
                LambdaQueryWrapper<AppOrder> aoq = new LambdaQueryWrapper<>();
                if (bo.getType()==6){
                    aoq.eq(AppOrder::getOrderStatus ,10);
                    aoq.isNull(AppOrder::getUnitPrice);
                }
                if (bo.getType()==7){
                  aoq.isNotNull(AppOrder::getUnitPrice);
                }
                List<AppOrder> appOrders = appOrderMapper.selectList(aoq);
                if (!CollUtil.isEmpty(appOrders)){
                    List<String> planId = appOrders.stream().map(AppOrder::getPlanId).toList();
                    lqw.in(AppProcurementPlan::getPlanCode,planId);
                }else {
                    return TableDataInfo.build(new Page<>());
                }
            }

            //8->待出库
            if (bo.getType()==8){
                LambdaQueryWrapper<AppOrder> aoq = new LambdaQueryWrapper<>();
                aoq.eq(AppOrder::getOrderStatus,3);
                List<AppOrder> appOrders = appOrderMapper.selectList(aoq);
                if (!CollUtil.isEmpty(appOrders)){
                    List<String> planId = appOrders.stream().map(AppOrder::getPlanId).toList();
                    lqw.in(AppProcurementPlan::getPlanCode,planId);
                }else {
                    return TableDataInfo.build(new Page<>());
                }
            }


            //9->已出库
            if (bo.getType()==9){
                //查询出库记录
                LambdaQueryWrapper<AppWarehouseRecord> ar = new LambdaQueryWrapper<>();
                ar.eq(AppWarehouseRecord::getType,1);
                List<AppWarehouseRecord> appWarehouseRecords = appWarehouseRecordMapper.selectList(ar);
                if (!CollUtil.isEmpty(appWarehouseRecords)){
                    List<String> planId = appWarehouseRecords.stream().map(AppWarehouseRecord::getPlanCode).toList();
                    lqw.in(AppProcurementPlan::getPlanCode,planId);
                }else {
                    return TableDataInfo.build(new Page<>());
                }
            }

            //10->已退费
            if (bo.getType()==10){
                LambdaQueryWrapper<AppOrder> aoq = new LambdaQueryWrapper<>();
                aoq.eq(AppOrder::getOrderStatus,13);
                List<AppOrder> appOrders = appOrderMapper.selectList(aoq);
                if (!CollUtil.isEmpty(appOrders)){
                    List<String> planId = appOrders.stream().map(AppOrder::getPlanId).toList();
                    lqw.in(AppProcurementPlan::getPlanCode,planId);
                }else {
                    return TableDataInfo.build(new Page<>());
                }
            }

            if (bo.getType()==11 || bo.getType()==12){
                LambdaQueryWrapper<AppOrder> aoq = new LambdaQueryWrapper<>();
                if (bo.getType()==11){
                    aoq.isNull(AppOrder::getUnitPrice);
                }else if (bo.getType()==12){
                    aoq.isNotNull(AppOrder::getUnitPrice);
                }
                List<AppOrder> appOrders = appOrderMapper.selectList(aoq);
                if (!CollUtil.isEmpty(appOrders)){
                    List<String> planId = appOrders.stream().map(AppOrder::getPlanId).toList();
                    lqw.in(AppProcurementPlan::getPlanCode,planId);
                }else {
                    return TableDataInfo.build(new Page<>());
                }
            }



        }
        if (bo.getOrderStatus()!=null){
            if (bo.getOrderStatus()==3){
                lqw.eq(AppProcurementPlan::getStayCarrier,1);
            }
        }

        Page<AppProcurementPlanVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        //查询是否有订单
        if (!CollUtil.isEmpty(result.getRecords())){
            result.getRecords().forEach(appProcurementPlanVo -> {
                //查询是否有订单
                LambdaQueryWrapper<AppOrder> appOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
                appOrderLambdaQueryWrapper.eq(AppOrder::getPlanId,appProcurementPlanVo.getPlanCode());
                appOrderLambdaQueryWrapper.eq(bo.getOrderStatus()!=null,AppOrder::getOrderStatus,bo.getOrderStatus());
                List<AppOrder> appOrders = appOrderMapper.selectList(appOrderLambdaQueryWrapper);
                if (!CollUtil.isEmpty(appOrders)){
                    //设置订单id
                    appProcurementPlanVo.setOrderId(CollUtil.getLast(appOrders).getOrderId());
                    Long warehouseId = CollUtil.getLast(appOrders).getWarehouseId();
                    appProcurementPlanVo.setLength(CollUtil.getLast(appOrders).getLength());
                    appProcurementPlanVo.setWidth(CollUtil.getLast(appOrders).getWidth());
                    appProcurementPlanVo.setHeight(CollUtil.getLast(appOrders).getHeight());
                    LambdaQueryWrapper<AppWarehouse> appWarehouseLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    appWarehouseLambdaQueryWrapper.eq(AppWarehouse::getStoreId,warehouseId);
                    List<AppWarehouse> appWarehouses = appWarehouseMapper.selectList(appWarehouseLambdaQueryWrapper);
                    if (!CollUtil.isEmpty(appWarehouses)){
                        appProcurementPlanVo.setWarehouseName(appWarehouses.get(0).getName());
                    }
                }
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的采购计划列表
     *
     * @param bo 查询条件
     * @return 采购计划列表
     */
    @Override
    public List<AppProcurementPlanVo> queryList(AppProcurementPlanBo bo) {
        LambdaQueryWrapper<AppProcurementPlan> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppProcurementPlan> buildQueryWrapper(AppProcurementPlanBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppProcurementPlan> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(AppProcurementPlan::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getPlanCode()), AppProcurementPlan::getPlanCode, bo.getPlanCode());
        lqw.eq(bo.getPlanType() != null, AppProcurementPlan::getPlanType, bo.getPlanType());
        lqw.eq(bo.getQuarterNum() != null, AppProcurementPlan::getQuarterNum, bo.getQuarterNum());
        lqw.eq(bo.getCompanyId() != null, AppProcurementPlan::getCompanyId, bo.getCompanyId());
        lqw.like(StringUtils.isNotBlank(bo.getCompanyName()), AppProcurementPlan::getCompanyName, bo.getCompanyName());
        lqw.eq(bo.getAuditStatus() != null, AppProcurementPlan::getAuditStatus, bo.getAuditStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getFailReason()), AppProcurementPlan::getFailReason, bo.getFailReason());
        return lqw;
    }

    /**
     * 新增采购计划
     *
     * @param bo 采购计划
     * @return 是否新增成功
     */
    @Override
    public String insertByBo(AppProcurementPlanBo bo) {
        AppProcurementPlan add = BeanUtil.toBean(bo, AppProcurementPlan.class);
        PlanSum planSum = DateUtils.getPlanSum();
        add.setQuarterNum(Long.valueOf(planSum.getQuarter()));
        add.setMouthNum(Long.valueOf(planSum.getMonth()));
        add.setDayNum(Long.valueOf(planSum.getDay()));

        validEntityBeforeSave(add);
        //设置采购计划编号 并将 采购详情写入数据库
        String id = RandomUtils.generateId();
        add.setPlanCode(id);
        //设置采购详情
        String tenantId = LoginHelper.getLoginUser().getTenantId();
        add.setTenantId(tenantId);
        List<AppProcurementDetail> appProcurementDetails = bo.getAppProcurementDetails();
        for (AppProcurementDetail appProcurementDetail : appProcurementDetails) {
            appProcurementDetail.setPlanCode(id);
            appProcurementDetail.setTenantId(tenantId);
        }
        iAppProcurementDetailService.insertBatch(appProcurementDetails);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return id;
    }

    /**
     * 修改采购计划
     *
     * @param bo 采购计划
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(AppProcurementPlanBo bo) {
        AppProcurementPlan update = MapstructUtils.convert(bo, AppProcurementPlan.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppProcurementPlan entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除采购计划信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public TotalPlanVo total(TotalPlanBo totalPlanBo) {
        //全部公司汇总
        if (totalPlanBo.getType() == 0){
            //查询全部采购详情记录
            List<AppProcurementDetail> appProcurementDetails =
                appProcurementDetailMapper.selectList();

            if (CollUtil.isEmpty(appProcurementDetails)){
                return new TotalPlanVo();
            }

            //这里的key 为 1-1 类型 分类id-原料id
            Map<String, List<AppProcurementDetail>> groupedMap = appProcurementDetails.stream()
                .collect(Collectors.groupingBy(item ->
                    item.getCategoryId() + "-" + item.getMaterialTypeId()
                ));
            Map<Long, String> categoryMap = iAppCategoryService.selAllMap();
            Map<Long, String> materialMap = iAppMaterialService.selAllMap();

            TotalPlanVo totalPlanVo = new TotalPlanVo();
            List<AppProcurementDetail> appProcurementDetailList = new ArrayList<>();
            for (Map.Entry<String, List<AppProcurementDetail>> entry : groupedMap.entrySet()) {
                String[] split = entry.getKey().split("-");
                AppProcurementDetail procurementDetail = new AppProcurementDetail();
                procurementDetail.setCategoryName(categoryMap.get(Long.parseLong(split[0])));
                procurementDetail.setMaterialName(materialMap.get(Long.parseLong(split[1])));
                List<AppProcurementDetail> value = entry.getValue();
                //统计总吨数
                long totalWeight = value.stream().mapToLong(AppProcurementDetail::getPlannedWeight).sum();
                //统计总车数
                long totalTruckNum = value.stream().mapToLong(AppProcurementDetail::getPlannedTruckNum).sum();
                procurementDetail.setPlannedWeight(totalWeight);
                procurementDetail.setPlannedTruckNum(totalTruckNum);
                appProcurementDetailList.add(procurementDetail);
            }
            totalPlanVo.setAppProcurementDetailVos(appProcurementDetailList);
            return totalPlanVo;
            //查询指定公司汇总
        }else if (totalPlanBo.getType() == 1){
            //查询公司名称
            LambdaQueryWrapper<SysTenant> sysTenantLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysTenantLambdaQueryWrapper.eq(SysTenant::getId, totalPlanBo.getCompanyId());
            SysTenant sysTenant = sysTenantMapper.selectOne(sysTenantLambdaQueryWrapper);
            totalPlanBo.setCompanyName(sysTenant.getCompanyName());

            TotalPlanVo totalPlanVo = new TotalPlanVo();
            List<AppProcurementDetail> appProcurementDetailList = new ArrayList<>();
            String companyId = totalPlanBo.getCompanyId();
            String companyName = totalPlanBo.getCompanyName();
            PlanSum planSum = DateUtils.getPlanSum();
            //查年
            totalPlanVo.setAppYear(getPlanTotal(companyName, 0, 0));
            //查季度
            totalPlanVo.setAppQuarter(getPlanTotal(companyName, 1, planSum.getQuarter()));
            //查月
            totalPlanVo.setAppMouth(getPlanTotal(companyName,2,planSum.getMonth()));
            //查日
            totalPlanVo.setAppDay(getPlanTotal(companyName,3,planSum.getDay()));

            totalPlanVo.setAppProcurementDetailVos(appProcurementDetailList);
            totalPlanVo.setCompanyId(Long.parseLong(companyId));
            totalPlanVo.setCompanyName(companyName);
            return totalPlanVo;


        }




        return new TotalPlanVo();
    }


    public List<AppProcurementDetail> getPlanTotal(String companyName,Integer planType,Integer sum){
        List<AppProcurementDetail> appProcurementDetailList = new ArrayList<>();
        Map<Long, String> categoryMap = iAppCategoryService.selAllMap();
        Map<Long, String> materialMap = iAppMaterialService.selAllMap();
        LambdaQueryWrapper<AppProcurementPlan> aq = new LambdaQueryWrapper<>();
        aq.eq(StringUtils.isNotBlank(companyName),AppProcurementPlan::getCompanyName, companyName);
        if (planType == 1){
            aq.eq(AppProcurementPlan::getQuarterNum, sum);
        }
        if (planType == 2){
            aq.eq(AppProcurementPlan::getMouthNum, sum);
        }
        if (planType == 3){
            aq.eq(AppProcurementPlan::getDayNum, sum);
        }
        List<AppProcurementPlan> appProcurementPlans = baseMapper.selectList(aq);
        if (CollUtil.isEmpty(appProcurementPlans)){
            return List.of();
        }
        Set<String> planCodes = appProcurementPlans.stream().map(AppProcurementPlan::getPlanCode).collect(Collectors.toSet());
        List<AppProcurementDetail> appProcurementDetails = appProcurementDetailMapper.selectList(new LambdaQueryWrapper<AppProcurementDetail>()
            .in(AppProcurementDetail::getPlanCode, planCodes));

        Map<String, List<AppProcurementDetail>> groupedMap = appProcurementDetails.stream()
            .collect(Collectors.groupingBy(item ->
                item.getCategoryId() + "-" + item.getMaterialTypeId()
            ));
        for (Map.Entry<String, List<AppProcurementDetail>> entry : groupedMap.entrySet()) {
            String[] split = entry.getKey().split("-");
            AppProcurementDetail procurementDetail = new AppProcurementDetail();
            procurementDetail.setCategoryName(categoryMap.get(Long.parseLong(split[0])));
            procurementDetail.setMaterialName(materialMap.get(Long.parseLong(split[1])));
            List<AppProcurementDetail> value = entry.getValue();
            //统计总吨数
            long totalWeight = value.stream().mapToLong(AppProcurementDetail::getPlannedWeight).sum();
            //统计总车数
            long totalTruckNum = value.stream().mapToLong(AppProcurementDetail::getPlannedTruckNum).sum();
            procurementDetail.setPlannedWeight(totalWeight);
            procurementDetail.setPlannedTruckNum(totalTruckNum);
            appProcurementDetailList.add(procurementDetail);
        }
        return appProcurementDetailList;
    }
}
